package com.automation.utils;
import io.appium.java_client.AppiumBy;
import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.Map;

public class AppiumUtils {
    public static WebElement waitForElement(AndroidDriver driver, By locator, int timeoutSec) {
        return new WebDriverWait(driver, Duration.ofSeconds(timeoutSec))
                .until(ExpectedConditions.visibilityOfElementLocated(locator));
    }

    public static boolean isElementPresent(AndroidDriver driver, By locator, int timeoutSec) {
        try {
            waitForElement(driver, locator, timeoutSec);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void scrollToText(AndroidDriver driver, String text) {
        driver.findElement(AppiumBy.androidUIAutomator(
                "new UiScrollable(new UiSelector().scrollable(true)).scrollIntoView(new UiSelector().textContains(\"" + text + "\"))"
        ));
    }

    public static void scrollDown(AndroidDriver driver) {
        driver.executeScript("mobile: scrollGesture", Map.of(
                "left", 100, "top", 500,
                "width", 500, "height", 1000,
                "direction", "down",
                "percent", 3.0
        ));
    }
}